package com.example.util;

import com.example.common.constant.Const;
import io.jsonwebtoken.*;
import lombok.Data;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;

import java.util.Date;

@Data
@Component
@ConfigurationProperties(prefix = "my-jwt")
public class JwtUtil {

    private long expire;
    private String secret;
    private String header;

    @Autowired
    RedisUtil redisUtil;

    //生成Jwt
    public String generateToken(String userName){

        Date nowDate = new Date();
        Date expireDate = new Date(nowDate.getTime() + 1000 * expire);
        String jwt = Jwts.builder()
                        .setHeaderParam("typ","JWT")
                        .setSubject(userName)
                        .setIssuedAt(nowDate)
                        .setExpiration(expireDate)
                        .signWith(SignatureAlgorithm.HS512,secret)
                        .compact();
        redisUtil.set(Const.PREFIX_JWT+userName, jwt,9000);
        return jwt;
    }

    //解析Jwt
    public Claims getClaimByToken(String jwt){
        try {
            return Jwts.parser()
                    .setSigningKey(secret)
                    .parseClaimsJws(jwt)
                    .getBody();
        } catch (Exception e) {
            return null;
        }
    }
}
